<template>
  <div class="beds-add">
    <DynamicForm :rulesForm="state.bedAdd" :rules="rules" @click="callBack" :refresh="state.refresh"/>
  </div>
</template>

<script lang="ts" setup>

import {ref, onMounted, defineEmits, reactive} from 'vue';

import {ElMessage} from 'element-plus';
import {useRoute} from 'vue-router';

import DynamicForm from '@/components/layout/form/dynamic-form.vue';

import {bedAddForms, bedAddRules} from '@/assets/script/monitor/forms/bed/add-form';
import {Options} from '@/components/layout/common/common';
import {listConstByDictionaryCodesApi} from '@/api/dictionary';
import {addBmsBedApi, listBmsBedApi, modifyBmsBedApi} from '@/api/bed';
import {addPersonnelForms} from "@/assets/script/monitor/forms/personnel/personnel-form";

const dynamicFormRef = ref(DynamicForm)
const rules = bedAddRules
const router = useRoute()

const emits = defineEmits<{ (e: 'appClick', data: object): void }>()

const state = reactive({
  bedAdd: JSON.parse(JSON.stringify(bedAddForms)),
  refresh: 0 as number,
  bed: {} as any
})

onMounted(() => {
  state.bedAdd[0].card.forEach((e: any) => {
    e[e.name] = ''
  })
  state.refresh = Math.random()
  listBedTypeByDictionaryCodes();
  if (router.query && router.query.id) {
    findBedById(router.query.id as any)
  }
})

const callBack = (data: any) => {
  switch (data.type || '') {
    case 'submit':
      // eslint-disable-next-line no-case-declarations
      let params = data.data
      if (params['bedName']) {
        params['name'] = params['bedName']
      }
      if(params['bedTypeIdName']) {
        params['bedTypeName'] = params['bedTypeIdName']
      }
      if (!params['space'] || params['space'].length !== 3) {
        ElMessage.warning('必须选择房间！')
        return
      } else {
        const space = params.space;
        const spaceName = params.spaceName;
        params['storey'] = space[0]
        params['storeyName'] = spaceName[0]
        params['floor'] = space[1]
        params['floorName'] = spaceName[1]
        params['room'] = space[2]
        params['roomName'] = spaceName[2]
      }
      if (state.bed && state.bed.id) {
        params['id'] = state.bed.id
      }
      modifyBed(params)
      break
    default:
      break
  }
}

const findBedById = (id: string) => {
  listBmsBedApi({id}).then((data: any) => {
    state.bed = data[0]
    const card = state.bedAdd[0].card
    card.forEach((e: any) => {
      if (!e.line) {
        switch (e.name) {
          case 'bedName':
            e[e.name] = state.bed['name']
            break
          case 'space':
            e[e.name] = [state.bed.storey, state.bed.floor, state.bed.room]
            break
          default:
            e[e.name] = state.bed[e.name]
            break
        }
      }
    })
    state.refresh = Math.random()
  })
}

const modifyBed = (data: any) => {
  if (data['id']) {
    modifyBmsBedApi(data).then((e: any) => {
      ElMessage.success('修改成功！')
      state.bed = {}
      emits('appClick', {type: 'closeTab', data: router.path})
    })
  } else {
    addBmsBedApi(data).then((e: any) => {
      ElMessage.success('添加成功！')
      state.bed = {}
      emits('appClick', {type: 'closeTab', data: router.path})
    })
  }
}


const listBedTypeByDictionaryCodes = () => {
  listConstByDictionaryCodesApi(['charge_type', 'storey', 'floor', 'room']).then((data: any) => {
    const card = state.bedAdd[0].card
    const bedType = card.find((f: any) => f.name === 'bedTypeId')
    if (bedType) {
      bedType.options = []
    }
    const bedTypes = data.filter((f: any) => f.dictionaryCode === 'charge_type' && f.parentCode === 'bed_type')
    bedTypes?.forEach((e: any) => {
      bedType?.options?.push({label: e.constName, value: e.constCode})
    })

    // 空间信息
    const space = card.find((f: any) => f.name === 'space')
    if (space) {
      space.options = []
    }
    const storeys = data.filter((f: any) => f.dictionaryCode === 'storey')
    storeys?.forEach((e: any) => {
      const storey: Options = {label: e.constName, value: e.constCode, children: []}
      const floors = data.filter((f: any) => f.parentCode === e.constCode)
      floors?.forEach((r: any) => {
        const floor: Options = {label: r.constName, value: r.constCode, children: []}
        const rooms = data.filter((f: any) => f.parentCode === r.constCode)
        rooms?.forEach((m: any) => {
          const room: Options = {label: m.constName, value: m.constCode}
          floor.children?.push(room)
        })
        storey.children?.push(floor)
      })
      space?.options?.push(storey)
    })
  })
}

</script>